﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Configuration;
using System.Web.Configuration;
using System.Collections.Specialized;

namespace Utils.DC.Web.UI
{
    public class DCHttpModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(DCRewrite_BeginRequest);
        }

        protected virtual void DCRewrite_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            string url = app.Request.RawUrl;

            string[] notRewriteURL = ConfigurationManager.AppSettings["NotRewriteURL"].Split(new char[] { ',' });
            //Begirequest co the la request cua file css, axd, aspx,v.v...
            //Phai check xem neu duoi file la .aspx thi moi rewrite
            try
            {
                if (url.IndexOf(".") != -1)
                {
                    if (url.Substring(url.IndexOf(".") + 1, 4) == "aspx")
                    {
                        //Xoa ki tu #,? trong url
                        url = url.Replace("#", "");
                        if(url.IndexOf("?") != -1)
                            url = url.Substring(0,url.IndexOf("?"));
                        url = url.ToLower();

                        //Check xem day co phai la form thao tac cua admin
                        if (url == "/" || url == "/default.aspx")
                        {
                            HttpContext.Current.Items.Add("PageSettings", PageSettings.GetDefaultPageSettings((byte)PageSettings.PAGE_TYPE.User));
                        }
                        else if(url == "/admin/default.aspx" || url == "/admin/")
                        {
                            HttpContext.Current.Items.Add("PageSettings", PageSettings.GetDefaultPageSettings((byte)PageSettings.PAGE_TYPE.Admin));
                        }
                        else if (url.IndexOf("/admin/form/") == -1)
                        {
                            //Kiem tra cac duong link trong web config
                            if (notRewriteURL != null && notRewriteURL.Length > 0)
                            {
                                foreach (string s in notRewriteURL)
                                {
                                    if (url == s.ToLower())
                                    {
                                        return;
                                    }
                                }
                            }

                            string queryString = "";
                            if (app.Request.QueryString != null && app.Request.QueryString.Count > 0)
                            {
                                for (int i = 0; i < app.Request.QueryString.Count; i++)
                                {
                                    queryString += app.Request.QueryString.Keys[i] + "=" + app.Request.QueryString[i] + "&";
                                }
                            }
                            Rewrite(url, app, queryString);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }

        private void Rewrite(String Path, HttpApplication app, string queryString)
        {
            PageSettings pageSettings = PageUtility.GetCurrentPage(Path);

            HttpContext.Current.Items.Add("PageSettings", pageSettings);
            //app.Context.RewritePath("/Admin/Default.aspx");

            //TODO Bo phan  o admin
            try
            {
                if (pageSettings.IsAdmin)
                {
                    app.Context.RewritePath("/Admin/Default.aspx?id=" + pageSettings.PageID + "&" + queryString);
                }
                else
                {
                    //if (pageSettings.FunctionType.Trim().ToLower() == "home")
                    //{
                        app.Context.RewritePath("/Default.aspx?id=" + pageSettings.PageID + "&" + queryString);
                    //}
                    //else
                    //{
                    //    app.Context.RewritePath("/Module/" + pageSettings.FunctionType.Trim() + "/Default.aspx?id=" + pageSettings.PageID);
                    //}
                }
            }
            catch (Exception e)
            {
                try
                {
                    app.Context.RewritePath(WebConfigurationManager.AppSettings["DefaultPage"]);
                }
                catch (Exception ex)
                {
                    app.Context.RewritePath("/Default.aspx");
                }
            }
        }


        #endregion
    }
}
